package top.hcode.hoj.dao.course;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hcode.hoj.mapper.CourseMapper;
import top.hcode.hoj.mapper.CourseSectionMapper;
import top.hcode.hoj.pojo.entity.course.Course;
import top.hcode.hoj.pojo.entity.course.CourseSection;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author orangej
 * @since 2024/12/18
 */
@Service
public class CourseSectionDao extends ServiceImpl<CourseSectionMapper, CourseSection> {

    @Autowired
    private CourseMapper courseMapper;

    public void loadCourse(CourseSection courseSection) {
        if (courseSection != null && courseSection.getCourseId() != null) {
            courseSection.setCourse(courseMapper.selectById(courseSection.getCourseId()));
        }
    }

    public void loadCourse(List<CourseSection> sectionList) {
        if (sectionList != null && !sectionList.isEmpty()) {
            List<Long> courseIdList = sectionList.stream().map(CourseSection::getCourseId).collect(Collectors.toList());
            Map<Long, Course> courseMap = courseMapper.selectBatchIds(courseIdList).stream()
                            .collect(Collectors.toMap(Course::getId, course -> course));
            for (CourseSection section : sectionList) {
                section.setCourse(courseMap.get(section.getCourseId()));
            }
        }
    }

    public int getNextSortOrder(Long courseId) {
        Integer max = baseMapper.getMaxSortOrder(courseId);
        return max == null ? 1 : max + 1;
    }

    public List<CourseSection> listChildrenOf(Long id) {
        QueryWrapper<CourseSection> query = new QueryWrapper<>();
        query.eq("parent_id", id).orderByAsc("sort_order");
        return baseMapper.selectList(query);
    }
}
